.text
.section .rodata
.align 3
.LC0:
    .string "Enter %d golf scores:\n"
.align  3
.LC1:
    .string "%d"
.align  3
.LC2:
    .string "the scores read in are as follows:"
.align  3
.LC3:
    .string "%5d"
.align  3
.LC5:
    .string "Sum of scores = %d, average = %.2f\n"
.align  3
.LC7:
    .string "That's a handicap of %0.f.\n"

.section .rodata
.align  2
.LC4:
    .word   1077936128
.align  2
.LC6:
    .word   1116733440

.text
.globl main
.type main, @function
main:
    // 是否也需要像x86_64一样，16位对齐？
    addi sp, sp, 40
    sd ra, 32(sp)
    sd s0, 24(sp)
    addi s0, sp, 40

    // -20(s0) /* index */
    // -32(s0) /* score */
    // -36(s0) /* sum */
    // -40(s0) /* average */
    li a5, 0
    sd a5, -36(s0) /* sum */

    li a5, 3
    mv a1, a5 // 相当于 add a1, a5, zero
    lui a5, %hi(.LC0)
    addi a0, a5, %lo(.LC0)
    call printf

    sw zero, -20(s0) /* index */
    j .L2
.L1:
    addi a4, s0, -32
    lw a5, -20(s0) /* index */
    slli a5, a5, 2
    add a5, a4, a5
    mv a1, a5
    lui a5, %hi(.LC1)
    addi a0, a5, %lo(.LC1)
    call scanf
    lw a5, -20(s0) /* index */
    addiw a5, a5, 1
    sw a5, -20(s0) /* index */
.L2:
    lw a5, -20(s0) /* index */
    // 符号扩展到a4
    sext.w a4, a5
    li a5, 2
    ble a4, a5, .L1

    lui a5, %hi(.LC2)
    addi a0, a5, %lo(.LC2)
    call puts

    sw zero, -20(s0) /* index */
    j .L4
.L3:
    addi a4, s0, -32
    lw a5, -20(s0) /* index */
    slli a5, a5, 2
    add a5, a4, a5
    lw a1, 0(a5)
    lui a5, %hi(.LC3)
    addi a0, a5, %lo(.LC3)
    call printf
    lw a5, -20(s0) /* index */
    addiw a5, a5, 1
    sw a5, -20(s0) /* index */
.L4:
    lw a5, -20(s0) /* index */
    sext.w a4, a5
    li a5, 2
    ble a4, a5, .L3

    li a0, 10
    call putchar

    sw zero, -20(s0) /* index */
    j .L6
.L5:
    addi a4, s0, -32
    lw a5, -20(s0) /* index */
    slliw a5, a5, 2
    add a5, a4, a5
    // score[index]
    lw a5, 0(a5)
    lw a4, -36(s0) /* sum */
    addw a5, a4, a5
    sw a5, -36(s0) /* sum */
    lw a5, -20(s0) /* index */
    addiw a5, a5, 1
    sw a5, -20(s0) /* index */
.L6:
    lw a4, -20(s0) /* index */
    sext.w a4, a4
    li a5, 2
    ble a4, a5, .L5
    
    lw a5, -36(s0) /* sum */
    fcvt.s.w fa4, a5
    lui a5, %hi(.LC4)
    flw fa5, %lo(.LC4)(a5)
    fdiv.s fa5, fa4, fa5
    fsw fa5, -40(s0) /* average */
    flw fa5, -40(s0) /* average */
    fcvt.d.s fa5, fa5
    // 这里为什么是把第二个参数放在a2，在function_declare_prototype中float的参数是放在fa0的？
    fmv.x.d a2, fa5
    lw a5, -36(s0) /* sum */
    mv a1, a5
    lui a5, %hi(.LC5)
    addi a0, a5, %lo(.LC5)
    call printf

    flw fa4, -40(s0) /* average */
    lui a5, %hi(.LC6)
    flw fa5, %lo(.LC6)(a5)
    fsub.s fa5, fa4, fa5
    fcvt.d.s fa5, fa5
    fmv.x.d a1, fa5
    lui a5, %hi(.LC7)
    addi a0, a5, %lo(.LC7)
    call printf

    li a0, 0
    ld ra, 32(sp)
    ld s0, 24(sp)
    addi sp, sp, 40
    jr ra

